package com.cn.appcore.ext

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.graphics.*
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.Checkable
import android.widget.EditText
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.ToastUtils
import com.cn.appcore.R
import com.cn.appcore.config.AppConfig
import com.cn.appcore.utils.NLog
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.math.RoundingMode
import java.text.DecimalFormat

/**
 * @author wxl
 * @date 2018/11/20
 * @desc
 */



/** 吐司 **/
fun showToast(msg: String?) {
    ToastUtils.make()
        .setGravity(Gravity.CENTER, 0, 0)
        .setBgResource(R.drawable.shape_toast_bg)
        .setTextColor(Color.parseColor("#FFFFFF"))
        .show(msg)
}
/** 颜色 **/
fun Context?.getCompatColor(res: Int): Int {
    if (this == null) {
        return Color.parseColor("#F92708")
    }
    return ContextCompat.getColor(this, res)
}
/** 资源id **/
fun Context?.getCompatDrawable(res: Int): Drawable? {
    if (this == null) {
        return null
    }
    return ContextCompat.getDrawable(this, res)
}
/** 资源id **/
fun Fragment?.getCompatDrawable(res: Int): Drawable? {
    return this?.context.getCompatDrawable(res)
}
/** 颜色 **/
fun Fragment?.getCompatColor(res: Int): Int {
    return this?.context.getCompatColor(res)
}

/** 数值类型保留2位，返回 String**/
val Number.double_2: String
    get() {
        val format = DecimalFormat("0.00")
        format.roundingMode = RoundingMode.DOWN
        return format.format(toDouble())//format 返回的是字符串
    }

/** 字符串类型转 数值类型 保留2位，返回 String**/
val String?.double_2: String
    get() {
        return (this?.toDoubleOrNull() ?: 0.00).double_2
    }



/** 数值类型保留2位，返回 String**/
val Number.double_6: String
    get() {
        val format = DecimalFormat("0.000000")
        format.roundingMode = RoundingMode.DOWN
        return format.format(toDouble())//format 返回的是字符串
    }
/** 字符串类型转 数值类型 保留2位，返回 String**/
val String?.double_6: String
    get() {
        return (this?.toDoubleOrNull() ?: 0.000000).double_6
    }


// 扩展点击事件属性(重复点击时长)
var <T : View> T.lastClickTime: Long
    set(value) = setTag(1766613352, value)
    get() = getTag(1766613352) as? Long ?: 0

// 重复点击事件绑定
inline fun <T : View> T.setSingleClickListener(time: Long = 1000, crossinline block: (T) -> Unit) {
    setOnClickListener {
        val currentTimeMillis = System.currentTimeMillis()
        if (currentTimeMillis - lastClickTime > time || this is Checkable) {
            lastClickTime = currentTimeMillis
            block(this)
        }
    }
}
private var lastClickTime = 0L
fun View.setOnFastClickListener(action: (view: View) -> Unit) {
    setOnClickListener {
        val currentTime = System.currentTimeMillis()
        if (lastClickTime != 0L && (currentTime - lastClickTime < 800L)) {
            return@setOnClickListener
        }
        lastClickTime = currentTime
        action(it)
    }
}
/** 打开浏览器 **/
fun Context.openBrowser(url: String) {
    val uri: Uri = Uri.parse(url)
    val intent = Intent(Intent.ACTION_VIEW, uri)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    startActivity(intent)
}



/** editText 输入监听**/
inline fun EditText.textChanged(crossinline done: (s: String) -> Unit) {
    this.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(p0: Editable?) {
        }

        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        }

        override fun onTextChanged(sequence: CharSequence?, p1: Int, p2: Int, p3: Int) {
            done.invoke(sequence.toString())
        }
    })
}

/**复制文本*/
fun Context?.copyText(msg: CharSequence?) {
    val clipboard = this?.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
    clipboard?.setPrimaryClip(ClipData.newPlainText("code", msg))
    showToast("复制成功")
}

/**复制文本*/
fun TextView.copyText() {
    text?.let {
        if (it.isNotBlank()) {
            context.copyText(it)
        }
    }
}

private fun View.loadBitmapFromView(): Bitmap {
    val w = width
    val h = height
    val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
    val c = Canvas(bmp)
    c.drawColor(Color.WHITE)
    draw(c)
    return bmp
}
fun View.saveImageResultPath(): String {
    return saveImageResultPath(context, this.loadBitmapFromView())
}

//保存文件到指定路径
private fun saveImageResultPath(context: Context, bmp: Bitmap): String {
    // 首先保存图片
    val storePath = context.cacheDir.absolutePath + File.separator + "image"
    val appDir = File(storePath)
    if (!appDir.exists()) {
        appDir.mkdir()
    }
    val fileName = System.currentTimeMillis().toString() + ".jpg"
    val file = File(appDir, fileName)
    try {
        val fos = FileOutputStream(file)
        //通过io流的方式来压缩保存图片
        val isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos)
        fos.flush()
        fos.close()
        bmp.recycle()
        return file.absolutePath
    } catch (e: IOException) {
        e.printStackTrace()
    }
    return ""
}

fun saveBitmap(context: Context,bitmap: Bitmap,name:String): String? {
    val fileUrl = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES + "/JingYu/")
    if (!fileUrl!!.exists()) fileUrl.mkdirs()
    val fileName = "$name.png"
    val file = File(fileUrl, fileName)
    try {
        val fos = FileOutputStream(file)
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
        fos.flush()
        fos.close()
    } catch (e: Exception) {
        e.printStackTrace()
    }
    MediaStore.Images.Media.insertImage(context.contentResolver, BitmapFactory.decodeFile(file.absolutePath), fileName, null);
    // 最后通知图库更新
    context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://$file")))
    Log.d("保存本地图", "地址: $file")
    return file.absolutePath
}
fun saveBitmap(context: Context,v: View, name: String): String? {
    val bmp = Bitmap.createBitmap(v.width, v.height,
        Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bmp)
    v.draw(canvas)
    val fileUrl = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES + "/JingYu/")
    if (!fileUrl!!.exists()) fileUrl.mkdirs()
    val fileName = "$name.png"
    val file = File(fileUrl, fileName)
    try {
        val fos = FileOutputStream(file)
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos)
        fos.flush()
        fos.close()
    } catch (e: Exception) {
        e.printStackTrace()
    }
    MediaStore.Images.Media.insertImage(context.contentResolver, BitmapFactory.decodeFile(file.absolutePath), fileName, null);
    // 最后通知图库更新
    context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://$file")))
    Log.d("保存本地图", "地址: $file")
    return file.absolutePath
}
fun dp2px(dpValue: Float): Int {
    return (0.5f + dpValue * Resources.getSystem().displayMetrics.density).toInt()
}
/** dip to px**/
val Number.dp: Int get() = (this.toFloat() * Resources.getSystem().displayMetrics.density).toInt()



/** px to dp px**/
val Number.px: Int get() = (this.toFloat() / Resources.getSystem().displayMetrics.density).toInt()

fun String.toxx(start: Int = 0, end: Int = 0): String {
    if (TextUtils.isEmpty(this)) return ""
    if (length <= start) return this
    if (length - end <= start) return this
    val toCharArray = this.toCharArray()
    for (i in start until (length - end)) {
        toCharArray[i] = '*'
    }
    return String(toCharArray)
}

/**
 * 输入监听回调
 */
fun EditText.afterTextChangeListener(afterText: (String) -> Unit) {

    addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
            afterText.invoke(s.toString())
        }
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }
    })
}
//可见性相关
fun View.gone() {
    visibility = View.GONE
}

fun View.visible() {
    visibility = View.VISIBLE
}

fun View.invisible() {
    visibility = View.INVISIBLE
}

fun View.setGone(isGone:Boolean){
    visibility = if (isGone) View.GONE else View.VISIBLE
}

fun View.setVisible(isVisible:Boolean){
    visibility = if (isVisible) View.VISIBLE else View.INVISIBLE
}

fun TextView.addStrikethroughLine(){
    paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
}